<template>
    <TopNav :title="metaTitle" />
    <Listing
      v-if="items && items.results.length"
      :title="metaTitle"
      :items="items"
      :loading="loading"
      @loadMore="loadMore"
    />
  </template>
  
  <script setup>
  import { getListItem, getTrending, getTvShows } from "@/api";
  import TopNav from "@/components/TopNav.vue";
  import Listing from "@/components/Listing.vue";
  import { ref, computed } from "vue";
  import { useRoute } from "vue-router";
  
  const loading = ref(false);
  const items = ref(null);
  
  const route = useRoute();
  
  const metaTitle = computed(() => {
    return getListItem("tv", route.params.name).title;
  });
  
  
  const isTrending = computed(() => {
    return route.params.name === "trending"; 
  })
  
  if(isTrending.value ){
      getTrending('tv').then((res)=>{
          items.value = res; 
      })
  }else{
      getTvShows(route.params.name).then((res)=>{
          items.value = res;
      })
  }
  
  
  const loadMore = () => {
    loading.value = true;
  
    let request = getTvShows(route.params.name, items.value.page + 1);
    if (isTrending.value) {
      request = getTrending("tv", items.value.page + 1);
    }
  
    request
      .then((res) => {
        items.value.results = items.value.results.concat(res.results);
        items.value.page = res.page;
      })
      .finally(() => {
        loading.value = false;
      });
  };
  </script>
  